//
//  YWKLoginAndRegistModel.m
//  YWKUser
//
//  Created by Admin on 16/5/10.
//  Copyright © 2016年 iCareTech. All rights reserved.
//

#import "YWKLoginAndRegistModel.h"
#import "YWKFetchUserNameAPI.h"
#import "YWKFetchTelePhoneNumberAPI.h"
#import "YWKRegisterUserAPI.h"
#import "YWKRequestVerificationcodeAPI.h"
#import "YWKFindbackAndModifyPasswordAPI.h"
#import "YWKLoginAndRegistReformerKeys.h"
#import "YWKLoginAndRegistInfoFormer.h"
#import "YWKModifyPasswordAPI.h"
#import <DDLog.h>

#ifdef DEBUG
static int ddLogLevel = LOG_LEVEL_VERBOSE;
#else
static int ddLogLevel = LOG_LEVEL_OFF;
#endif

extern NSInteger SENDCOUNT;

@interface YWKLoginAndRegistModel ()<
RNAPIManagerApiCallBackDelegate,
RNAPIManagerParamSourceDelegate,
RNAPIManagerValidator
>

@property (nonatomic, strong)YWKFetchUserNameAPI * fetchUserNameAPI;
@property (nonatomic, strong)YWKFetchTelePhoneNumberAPI * fetchTelePhoneNumberAPI;
@property (nonatomic, strong)YWKRegisterUserAPI * registerUserAPI;
@property (nonatomic, strong)YWKRequestVerificationcodeAPI * requestVerificationCodeAPI;
@property (nonatomic, strong)YWKFindbackAndModifyPasswordAPI * modifyPasswordAPI;
@property (nonatomic, strong)YWKModifyPasswordAPI * setNewPasswordAPI;
@property (nonatomic, strong)YWKLoginAndRegistInfoFormer * userNameInformer;
@property (nonatomic, copy)NSString * userName;
@property (nonatomic, copy)NSString * telephone;
@property (nonatomic, strong)id dataList;
@property (nonatomic, strong)NSString * code;
@property (nonatomic, assign)NSInteger roleType;
@property (nonatomic, copy)NSString * password;
@property (nonatomic, copy)NSString * theNewPassword;

@end

@implementation YWKLoginAndRegistModel


- (void)fetchDataWithUserName:(NSString *)name{
    
    self.userName = name;
    [self fetchUserNameData];
}

- (void)fetchDataWithTelephone:(NSString *)telephone{
    
    self.telephone = telephone;
    [self fetchTelephoneNumberData];
}

- (void)requestVerificationCodeAPIWithTelephone:(NSString *)telephone{
    
    self.telephone = telephone;
    self.userName = nil;
    [self requestVerificationCode];
}

- (void)requestVerificationCodeAPIWithName:(NSString *)name{
    
    self.userName = name;
    self.telephone = nil;
    [self requestVerificationCode];
}

- (void)registerWithTelephone:(NSString *)phoneNumber
             verificationCode:(NSString *)code
                     password:(NSString *)password
                     roleType:(NSInteger)roleType{
    
    self.telephone = phoneNumber;
    self.code = code;
    self.password = password;
    self.roleType = roleType;
    [self registeruser];
}

- (void)modifyPasswordWithPhoneOrName:(NSString *)string
             verificationCode:(NSString *)code
                     password:(NSString *)password{
    
    self.userName = string;
    self.code = code;
    self.password = password;
    [self modifyPasswordRequest];
}

- (void)modifyPasswordWithPhoneOrName:(NSString *)string
                          oldPassword:(NSString *)old
                          newPassword:(NSString *)newPassword{
    self.userName = string;
    self.theNewPassword = newPassword;
    self.password = old;
    [self setNewPasswordRequest];
}

#pragma mark - RNAPIManagerParamSourceDelegate

- (NSDictionary *)paramsForApi:(RNAPIBaseManager *)manager
{
    if ([manager isKindOfClass:[YWKFetchUserNameAPI class]])
    {
        NSDictionary * params = @{
                                  @"userName":self.userName
                                  };
        DDLogInfo(@"paramsDic = %@", params);
        return params;
    }
    
    if ([manager isKindOfClass:[YWKFetchTelePhoneNumberAPI class]])
    {
        NSDictionary * params = @{
                                  @"mobile":self.telephone
                                  };
        DDLogInfo(@"paramsDic = %@", params);
        return params;
    }
    
    if ([manager isKindOfClass:[YWKRequestVerificationcodeAPI class]])
    {
        NSDictionary * params;
        if (!self.telephone)
        {
            params =  @{
                        @"userName":self.userName
                        };
        }
        else
        {
            params =  @{
                        @"phoneNumber":self.telephone
                        };
        }
       
        DDLogInfo(@"paramsDic = %@",params);
        return params;
    }
    
    /**
     *  如果需要扩展用户名注册，在此修改。
     */
    if ([manager isKindOfClass:[YWKRegisterUserAPI class]])
    {
        NSDictionary * params = @{
                                  @"mobile":self.telephone,
                                  @"password":self.password,
                                  @"roleType":@(self.roleType),
                                  @"verificationCode":self.code,
                                  };
        DDLogInfo(@"paramsDic = %@",params);
        return params;
    }
    /**
     *  找回密码
     */
    if ([manager isKindOfClass:[YWKFindbackAndModifyPasswordAPI class]])
    {
        NSDictionary * params = @{
                                   @"userName":self.userName,
                                   @"code":self.code,
                                   @"password":self.password
                                  };
        DDLogInfo(@"paramsDic = %@",params);
        return params;
    }
    /**
     *  登陆后修改密码
     */
    if ([manager isKindOfClass:[YWKModifyPasswordAPI class]])
    {
        NSDictionary * params = @{
                                  @"userName":self.userName,
                                  @"password":self.password,
                                  @"newPassword":self.theNewPassword,
                                  };
        DDLogInfo(@"paramsDic = %@",params);
        return params;
    }
    
    return nil;
}

#pragma mark - RNAPIManagerApiCallBackDelegate

- (void)managerCallAPIDidSuccess:(RNAPIBaseManager *)manager
{
    id response = [manager fetchDataWithReformer:self.userNameInformer];
    if([manager isKindOfClass:[YWKFetchUserNameAPI class]] ||
       [manager isKindOfClass:[YWKFetchTelePhoneNumberAPI class]])
    {
        DDLogInfo(@"response = %@",response);

        if ([self.loginAndRegistDelegate respondsToSelector:@selector(checkUserNameHasexisted:)]) {
           
            [self.loginAndRegistDelegate checkUserNameHasexisted:response];
        }
    }
    
    if([manager isKindOfClass:[YWKRequestVerificationcodeAPI class]])
    {
        DDLogInfo(@"response = %@",response);
        if ([response[@"result"] isEqualToNumber:@3]) {
            
            return;
        }
         self.code = response[@"code"];
        if ([self.loginAndRegistDelegate respondsToSelector:@selector(getVerificationCode:)]) {
            
            [self.loginAndRegistDelegate getVerificationCode:self.code];
        }
    }
    
    if([manager isKindOfClass:[YWKRegisterUserAPI class]])
    {
        DDLogInfo(@"response = %@",response);
        if ([self.loginAndRegistDelegate respondsToSelector:@selector(registResult:)]) {
            
            [self.loginAndRegistDelegate registResult:response];
        }
    }
    
    if([manager isKindOfClass:[YWKFindbackAndModifyPasswordAPI class]])
    {
        DDLogInfo(@"response = %@",response);
        if ([self.loginAndRegistDelegate respondsToSelector:@selector(modifyPasswordResult:)]) {
            
            [self.loginAndRegistDelegate modifyPasswordResult:response];
        }
    }
    
    if([manager isKindOfClass:[YWKModifyPasswordAPI class]])
    {
        DDLogInfo(@"response = %@",response);
        if ([self.loginAndRegistDelegate respondsToSelector:@selector(modifyPasswordResult:)]) {
            
            [self.loginAndRegistDelegate modifyPasswordResult:response];
        }
    }
}

- (void)managerCallAPIDidFailed:(RNAPIBaseManager *)manager
{
    DDLogInfo(@"RNAPIManagerErrorType = %zd errorMessage = %@",
          manager.errorType, manager.errorMessage);
    if ([self.loginAndRegistDelegate respondsToSelector:@selector(failedWithResponse:)]) {
    
        NSString * errorReason = @"请求异常";
        if (manager.errorType == RNAPIManagerErrorTypeNoNetWork) {
            
            errorReason = NSLocalizedString(@"网络不给力,稍后再试试", @"Network not to force , try again later");
        }
        if (manager.errorType == RNAPIManagerErrorTypeTimeout) {
            
            errorReason = NSLocalizedString(@"请求超时!", @"Timeout");
        }
        [self.loginAndRegistDelegate failedWithResponse:@{@"errorReason":errorReason}];
    }
}

#pragma mark - RNAPIManagerValidator

- (BOOL)manager:(RNAPIBaseManager *)manager isCorrectWithCallBackData:(NSDictionary *)data
{
    //解析基础字段
    id reformedData = [self.userNameInformer validateResponseData:data];
    DDLogInfo(@"reformaedData%@",reformedData);
    NSString * const kYWKRNResponseResult = @"result";
    
    if ([manager isKindOfClass:[YWKRegisterUserAPI class]]) {
        
        if (![reformedData[kYWKRNResponseResult] isEqualToNumber:@0] &&
            ![reformedData[kYWKRNResponseResult] isEqualToNumber:@21])
        {
            return NO;
        }
    }
    else if ([manager isKindOfClass:[YWKFindbackAndModifyPasswordAPI class]])
    {
        if (![reformedData[kYWKRNResponseResult] isEqualToNumber:@0] &&
            ![reformedData[kYWKRNResponseResult] isEqualToNumber:@11] &&
            ![reformedData[kYWKRNResponseResult] isEqualToNumber:@-1] &&
            ![reformedData[kYWKRNResponseResult] isEqualToNumber:@28])
        {
            return NO;
        }
        
    }
    else if ([manager isKindOfClass:[YWKFetchUserNameAPI class]])
    {
        if (![reformedData[kYWKRNResponseResult] isEqualToNumber:@0] &&
            ![reformedData[kYWKRNResponseResult] isEqualToNumber:@11] &&
            ![reformedData[kYWKRNResponseResult] isEqualToNumber:@20])
        {
                return NO;
        }
    }
    else if ([manager isKindOfClass:[YWKFetchTelePhoneNumberAPI class]])
    {
           if (![reformedData[kYWKRNResponseResult] isEqualToNumber:@0] &&
               ![reformedData[kYWKRNResponseResult] isEqualToNumber:@20] &&
               ![reformedData[kYWKRNResponseResult] isEqualToNumber:@12])
           {
               return NO;
           }
    }
    else if ([manager isKindOfClass:[YWKRequestVerificationcodeAPI class]])
    {
        if ([reformedData[kYWKRNResponseResult] isEqualToNumber:@3]) {
            
            if ([self.loginAndRegistDelegate respondsToSelector:@selector(getVerificationCodeFailed)]) {
                
                [self.loginAndRegistDelegate getVerificationCodeFailed];
            }
        }
        if (![reformedData[kYWKRNResponseResult] isEqualToNumber:@0] &&
            ![reformedData[kYWKRNResponseResult] isEqualToNumber:@20] &&
            ![reformedData[kYWKRNResponseResult] isEqualToNumber:@12] &&
            ![reformedData[kYWKRNResponseResult] isEqualToNumber:@3])
        {
            return NO;
        }
    }
    else if ([manager isKindOfClass:[YWKModifyPasswordAPI class]])
    {
        if (![reformedData[kYWKRNResponseResult] isEqualToNumber:@0])
        {
            return NO;
        }
    }
    return YES;
}

- (BOOL)manager:(RNAPIBaseManager *)manager isCorrectWithParamsData:(NSDictionary *)data
{
    return YES;
}


#pragma mark - RNAPIManagerCallbackDataReformer

- (id)manager:(RNAPIBaseManager *)manager reformData:(NSDictionary *)data
{
    return nil;
}

#pragma mark - private methods
/**
 *  请求数据
 */
- (void)fetchUserNameData
{
    [self.fetchUserNameAPI loadData];
}

/**
 *  请求数据
 */
- (void)fetchTelephoneNumberData
{
    
    [self.fetchTelePhoneNumberAPI loadData];
}

/**
 *  请求验证码数据
 */
- (void)requestVerificationCode
{
    
    [self.requestVerificationCodeAPI loadData];
}

/**
 *  注册数据
 */
- (void)registeruser
{
    
    [self.registerUserAPI loadData];
}

/**
 *  请求找回密码数据
 */
- (void)modifyPasswordRequest
{
    [self.modifyPasswordAPI loadData];
}

/**
 *  请求修改密码数据
 */
- (void)setNewPasswordRequest
{
    [self.setNewPasswordAPI loadData];
}

#pragma mark - setter && getter

- (YWKFetchUserNameAPI *)fetchUserNameAPI
{
    if (!_fetchUserNameAPI)
    {
        _fetchUserNameAPI = [[YWKFetchUserNameAPI alloc] init];
        _fetchUserNameAPI.delegate = self;
        _fetchUserNameAPI.paramSource = self;
        _fetchUserNameAPI.validator = self;
    }
    return _fetchUserNameAPI;
}

-(YWKFetchTelePhoneNumberAPI *)fetchTelePhoneNumberAPI{
    
    if (!_fetchTelePhoneNumberAPI)
    {
        _fetchTelePhoneNumberAPI = [[YWKFetchTelePhoneNumberAPI alloc] init];
        _fetchTelePhoneNumberAPI.delegate = self;
        _fetchTelePhoneNumberAPI.paramSource = self;
        _fetchTelePhoneNumberAPI.validator = self;
    }
    return _fetchTelePhoneNumberAPI;
}

-(YWKRegisterUserAPI *)registerUserAPI{
    
    if (!_registerUserAPI)
    {
        _registerUserAPI = [[YWKRegisterUserAPI alloc] init];
        _registerUserAPI.delegate = self;
        _registerUserAPI.paramSource = self;
        _registerUserAPI.validator = self;
    }
    return _registerUserAPI;
}

-(YWKLoginAndRegistInfoFormer *)userNameInformer{
    if (!_userNameInformer) {
        
        _userNameInformer = [[YWKLoginAndRegistInfoFormer alloc] init];
    }
    
    return _userNameInformer;
}

-(YWKRequestVerificationcodeAPI *)requestVerificationCodeAPI{
    
    if (!_requestVerificationCodeAPI)
    {
        _requestVerificationCodeAPI = [[YWKRequestVerificationcodeAPI alloc] init];
        _requestVerificationCodeAPI.delegate = self;
        _requestVerificationCodeAPI.paramSource = self;
        _requestVerificationCodeAPI.validator = self;
    }
    return _requestVerificationCodeAPI;
}

-(YWKFindbackAndModifyPasswordAPI *)modifyPasswordAPI{
    
    if (!_modifyPasswordAPI)
    {
        _modifyPasswordAPI = [[YWKFindbackAndModifyPasswordAPI alloc] init];
        _modifyPasswordAPI.delegate = self;
        _modifyPasswordAPI.paramSource = self;
        _modifyPasswordAPI.validator = self;
    }
    return _modifyPasswordAPI;
}

-(YWKModifyPasswordAPI *)setNewPasswordAPI{
    
    if (!_setNewPasswordAPI)
    {
        _setNewPasswordAPI = [[YWKModifyPasswordAPI alloc] init];
        _setNewPasswordAPI.delegate = self;
        _setNewPasswordAPI.paramSource = self;
        _setNewPasswordAPI.validator = self;
    }
    return _setNewPasswordAPI;
}
@end
